﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;


namespace 网络编程
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Dictionary<string,Socket> dicScoket=new Dictionary<string,Socket>();
        private void btStart_Click(object sender, EventArgs e)
        {
            try
            {
                Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Any;
                IPEndPoint port = new IPEndPoint(ip, Convert.ToInt32(tb2.Text));
                serverSocket.Bind(port);
                ShowMsg("监听成功");
                serverSocket.Listen(10);
                Thread th = new Thread(Listen);
                th.IsBackground = true;
                th.Start(serverSocket);
            }
            catch { }
        }
        private void ShowMsg(string str) 
        {
            tbx1.AppendText(str+"\r\n");
        }
        Socket socket;
        private void Listen(Object o) 
        {
            Socket serverSocket=o as Socket;
            while(true)
            {
                socket = serverSocket.Accept();
                dicScoket.Add(socket.RemoteEndPoint.ToString(), socket);
                cbx1.Items.Add(socket.RemoteEndPoint.ToString());
                ShowMsg(socket.RemoteEndPoint.ToString() + ":" + "已连接");
                Thread th = new Thread(Receive);
                th.IsBackground = true;
                th.Start(socket);
              
            }
        }
        private void Receive(Object o) 
        {
            Socket socket = o as Socket;
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024];
                    int[] num = new int[256];
                    int r = socket.Receive(buffer);
                    StringBuilder sb = new StringBuilder("");
                    if (r == 0) { break; }
                    for (int j = 0; j < r; j++)
                    {
                        num[j] = buffer[j] & 0xff;
                        sb.Append(Convert.ToString(num[j], 16).PadLeft(2, '0'));
                        sb.Append(" ");
                    }
                    ShowMsg(socket.RemoteEndPoint.ToString() + ":" + sb);

                }catch{}
            }

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        public static byte[] GetByteArray(string shex)
        {
            string[] ssArray = shex.Split(' ');
            List<byte> bytList = new List<byte>();
            foreach (var s in ssArray)
            {
                //将十六进制的字符串转换成数值
                bytList.Add(Convert.ToByte(s, 16));
            }
            //返回字节数组
            return bytList.ToArray();
        }

        private void btSend_Click(object o, EventArgs e)
        {
            Socket socket = o as Socket;
            try 
            {
                if(cbx1.SelectedItem==null)
                {
                    MessageBox.Show("请选中要发送的客户端哟");
                } 
                string str = tbx2.Text.ToString().Trim();
                string s = str.Replace(" ", "");
                byte[] buffer = GetByteArray(str);
                string ip = cbx1.SelectedItem.ToString();
                dicScoket[ip].Send(buffer);
                tbx2.Text = "";
                ShowMsg("我:"+str);
            }
            catch { }
           
        }
    }
}
